#include "client_socket.h"

#define MAX_BUFFER	1024

ClientSocket::ClientSocket(char* servername, int port)
{
	WSADATA wsaData;
	int error;
    
	int nHostPort;
    struct hostent* pHostInfo;   // holds info about a machine 
    struct sockaddr_in Address;  // Internet socket address stuct 
    long nHostAddress;
    char strHostName[HOST_NAME_SIZE];
    

    if (servername == NULL)
	{
		m_hSocket = SOCKET_ERROR;
		throw "No Server Specified";
	}
    else
    {
		strcpy(strHostName,servername);
		nHostPort=port;		//atoi(argv[2]);
    }
	//printf("Initializing socket dll\n");
	error = WSAStartup(MAKEWORD(2,0), &wsaData);	//WSAStartup initializes the windows socket DLL
													//MAKEWORD(2,2) makes a word for the version number of the DLL
													//wsaData--Not sure what this does, returns a value.
	if (error != 0)
	{
		printf("Unable to find a usable dll\n");
		m_hSocket = SOCKET_ERROR;
		throw "Winsock DLL not found";
	}

    //printf("Making a socket\n");

    // make a socket 
    m_hSocket=socket(AF_INET,SOCK_STREAM,0);			//returns a handle to the socket of the specified type.
													//using SOCK_STREAM tcp will be used.

    if(m_hSocket == SOCKET_ERROR)
    {
        printf("\nCould not make a socket\n");
		throw "Could not create a socket";
    }

    // get IP address from name 
    pHostInfo=gethostbyname(strHostName);
    // copy address into long 
    memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);	//read info from host machine so we can use it
																	//to communicate:  includes info about what socket 
																	//to connect to.

    // fill address struct 
    Address.sin_addr.s_addr=nHostAddress;							//communication structure of how to connect.
    Address.sin_port=htons(nHostPort);
    Address.sin_family=AF_INET;

    //printf("\nConnecting to %s on port %d\n",strHostName,nHostPort);

    // connect to host 
    if(connect(m_hSocket,(struct sockaddr*)&Address,sizeof(Address)) == SOCKET_ERROR)
    {
        printf("\nCould not connect to host\n");
		m_hSocket = SOCKET_ERROR;
		throw "Could not connect to host";
    }
}

int ClientSocket::SendMessage(char *message, int len) {
	int bsent = 0;

//	printf("message sent: %s\n", message);
	if ((bsent = send(m_hSocket, message, len, 0)) == SOCKET_ERROR) {
		printf("error sending socket message\n");
		exit(0);
		//quit = true;
	}

	return bsent;
}

int ClientSocket::ReadMessage(char *message) {
	int NumBytes = 0;

	memset(message, 0, MAX_BUFFER);
	NumBytes = recv(m_hSocket, message, 1024, 0);
	
	if (NumBytes == SOCKET_ERROR) {
		//quit = true;
		printf("lost socket connection\n");
		exit(0);
//		fprintf(stderr,"Socket Error\n");
//		throw "Error Reading From Socket";
	}

	return NumBytes;
}
